package com.btcode.reflect;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import java.io.IOException;
import java.util.List;

/**
 * 自动类加载项 自动判断是jar还是class
 *
 * @author gislin
 */
public class AutoClassLoader implements IClassLoader {

    private IClassFinder classFinder;

    private ILog log;

    public AutoClassLoader(IClassFinder classFinder) {
        log = MyLog.getInstance().getLogger(AutoClassLoader.class.getName());
        this.classFinder = classFinder;
    }

    public List<Class<?>> loadClass(Class<?> myClass, String packetName)
        throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {

        boolean isJar = isJar(myClass);

        IClassLoader classLoader;

        if (isJar) {
            classLoader = new JarClassLoader(classFinder);
        }
        else {
            classLoader = new FileClassLoader(classFinder);
        }

        log.info("扫描：" + packetName + ",isJar:" + isJar + ",classLoader:" + classLoader);

        List<Class<?>> classList = classLoader.loadClass(myClass, packetName);

        log.info("扫描结果：" + packetName + ",size:" + classList.size());

        return classList;
    }

    /**
     * 判断上下文的class是jar还是class
     */
    private boolean isJar(Class<?> myClass) {

        String className = myClass.getName();
        className = className.substring(className.lastIndexOf(".") + 1, className.length())
            + ".class";

        String resourcePath = myClass.getResource(className).toString();
        boolean isJar = resourcePath.startsWith("jar");

        return isJar;
    }

}
